package com.bhs.sansonglogistics.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;


import com.bhs.sansonglogistics.net.NetApi;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.net.RetrofitUtils;
import com.bhs.sansonglogistics.ui.login.OneClickLoginActivity;
import com.bhs.sansonglogistics.ui.login.PhoneNumberLoginActivity;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.pgyer.pgyersdk.PgyerSDKManager;


import org.json.JSONObject;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class BaseFragment extends Fragment {
    protected AppCompatActivity activity;
    protected View view;
    public NetApi netApi;
    private boolean isFirstLoad = true; // 是否第一次加载
    public LoadingPopupView loadingPopup;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(initLayout(), container, false);
        prestrain();
        return view;
    }

    public void prestrain() {
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = (AppCompatActivity) getActivity();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstLoad) {
            //创建网络请求接口对象实例
            netApi = RetrofitUtils.getInstance().getRetrofit().create(NetApi.class);
            initView(view);
            initData();
            isFirstLoad = false;
        }

        onResumes();
    }

    public void onResumes() {
    }

    public void networkRequest(Call<ResponseBody> dataCall, NetCallBack callBack) {
        networkRequestCode(dataCall, callBack, 0);
    }

    /**
     * 假如一个界面有两个网络请求传入requestCode用于区分
     */
    public void networkRequest(Call<ResponseBody> dataCall, NetCallBack callBack, int requestCode) {
        networkRequestCode(dataCall, callBack, requestCode);
    }

    private void networkRequestCode(Call<ResponseBody> dataCall, NetCallBack callBack, int requestCode) {
        //异步请求
        dataCall.enqueue(new Callback<ResponseBody>() {
            //请求成功回调
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.code() == 200) {
                    try {
                        String body = response.body().string();
                        JSONObject jsonObject = new JSONObject(body);
                        String code = jsonObject.getString("code");
                        if (code.equals("404")) {
                            SharedPreferencesUtils.clear(getContext(), "token");
                            startActivity(new Intent(getActivity(), PhoneNumberLoginActivity.class));
                        } else {
                            callBack.onResponse(requestCode, body, response);
                        }
                    } catch (Exception e) {
                        //手动上报异常
                        PgyerSDKManager.reportException(e);
                        e.printStackTrace();
                    }
                } else {
                    callBack.onFailure(requestCode);
                    ToastUtil.show("网络错误" + response.code() + response.message());
                }

            }

            //请求失败回调
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                callBack.onFailure(requestCode);
                if (!call.isCanceled()) {
                    ToastUtil.show("网络错误2" + t.toString());
                }
            }
        });
    }

    /**
     * 设置根布局
     */
    public abstract int initLayout();

    /**
     * 初始化布局
     */
    public abstract void initView(View root);

    /**
     * 设置数据
     */
    public abstract void initData();

    public void loadingPopupShow() {
        if (loadingPopup == null) {
            loadingPopup = (LoadingPopupView) new XPopup.Builder(getContext())
                    .dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false)
                    .isLightNavigationBar(true)
                    .asLoading("", LoadingPopupView.Style.ProgressBar)
                    .show();
        } else {
            loadingPopup.show();
        }
    }

    public void loadingPopupDismiss() {
        if (loadingPopup != null) {
            loadingPopup.dismiss();
        }
    }
}
